package com.yitiao.multithread;

import sun.misc.Unsafe;

import java.util.concurrent.TimeUnit;

public class DeadLockDemo {
    final static Object objectA = new Object();
    final static Object objectB = new Object();

    public volatile Integer i=0;

    public static void main(String[] args) {
        Unsafe unsafe = Unsafe.getUnsafe();
        unsafe.allocateMemory(7L);
        new Thread(()->{
            synchronized (objectA){
                System.out.println("--------A");
                // 以获取锁A，等待获取锁B，但此时B锁已被线程2占用
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (objectB){
                    System.out.println("---------B");
                }
            }
        }).start();

        new Thread(()->{
            // 获取B没毛病
            synchronized (objectB){
                System.out.println("--------B");
                // 等待A，但此时A已被线程1占用，且A正在等待线层2 释放的锁B
                // 死锁
                synchronized (objectA){
                    System.out.println("---------A");
                }
            }
        }).start();


    }
}
